package main.java.dao;

import main.java.util.JDBCUtil;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class BaseDAO {
    /**
     * 执行增删改的方法
     * @param sql    执行的sql语句
     * @param params 执行sql语句的参数，如果没有参数，则设为null
     * @return 受影响行数
     */
    public int executeUpdate(String sql, Object... params) throws Exception {
        Connection connection = JDBCUtil.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }
        ;
        int update = preparedStatement.executeUpdate();
        preparedStatement.close();
        JDBCUtil.releaseConnection(connection);
        return update;
    }

    /**
     * 通用查询方法
     */
    public <T> List<T> executeQuery(Class<T> clazz, String sql, Object... params) throws Exception {
        Connection connection = JDBCUtil.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }
        }

        ResultSet resultSet = preparedStatement.executeQuery();
        //获取结果集中的元数据对象
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        List<T> list = new ArrayList<>();
        while (resultSet.next()) {
            //通过反射创建一个对象
            T t = clazz.newInstance();
            for (int i = 0; i < columnCount; i++) {

                Object value = resultSet.getObject(i + 1);

                String fieldName = metaData.getColumnLabel(i + 1);
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                field.set(t, value);
            }
            list.add(t);
        }
        resultSet.close();
        preparedStatement.close();
        JDBCUtil.releaseConnection(connection);
        return list;
    }

    /**
     * 查询单条记录
     *
     */
    public <T> T executeQuerySingle(Class<T> clazz, String sql, Object... params) throws Exception {

        List<T> list = this.executeQuery(clazz, sql, params);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }
}
